package utils

import (
	"fmt"
	"io/ioutil"
	"os"
	"strconv"

	"gddgame.cc/galaxy/utils/system"
)

func CheckPid(pidFile string) (int, error) {
	pf, err := os.OpenFile(pidFile, os.O_RDWR, 0)
	defer pf.Close()
	if os.IsNotExist(err) {
		return 0, nil
	} else if err != nil {
		return 0, fmt.Errorf("pidfile check error:%v\n", err)
	} else {
		pd, _ := ioutil.ReadAll(pf)
		oldPid, err := strconv.Atoi(string(pd))
		if err := system.KillProcess(oldPid); err != nil {
			return 0, nil
		}
		return oldPid, err
	}
}

func MakePid(pidFile string) (int, error) {
	pf, err := os.OpenFile(pidFile, os.O_RDWR, 0)
	defer pf.Close()
	if os.IsNotExist(err) {
		pf, err = os.Create(pidFile)
		if err != nil {
			return 0, fmt.Errorf("create pid file error:%v\n", err)
		}
	} else if err != nil {
		return 0, fmt.Errorf("pidfile check error:%v\n", err)
	} else {
		pd, _ := ioutil.ReadAll(pf)
		oldPid, err := strconv.Atoi(string(pd))
		if err != nil {
			return 0, err
		}
		if err := system.KillProcess(oldPid); err == nil {
			return 0, fmt.Errorf("pid process exist error:%v\n", err)
		}
	}
	newPid := os.Getpid()
	if _, err = pf.Write([]byte(fmt.Sprintf("%d", newPid))); err != nil {
		return 0, fmt.Errorf("write pid failed:%v\n", err)
	}
	return newPid, nil
}

func RmPid(pidFile string) error {
	_, err := os.Stat(pidFile)
	if os.IsNotExist(err) {
		return nil
	} else {
		return os.Remove(pidFile)
	}
}
